package org.yu.lemon.platform.common.response;

import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import org.yu.lemon.platform.common.annotation.IgnoreResponse;
import org.yu.lemon.platform.common.domain.Result;
import org.yu.lemon.platform.common.utils.JsonUtil;

import java.util.Objects;

/**
 * @author wei
 * @date 2022/5/13 15:18
 */
@RestControllerAdvice
public class ResponseCustomAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(
            @NonNull MethodParameter methodParameter,
            @NonNull Class<? extends HttpMessageConverter<?>> aClass
    ) {
        // 标注了@RestController，且类及方法上都没有标注@IgnoreResponse的方法才进行包装
        return methodParameter.getDeclaringClass().isAnnotationPresent(RestController.class)
                && !methodParameter.getDeclaringClass().isAnnotationPresent(IgnoreResponse.class)
                && !Objects.requireNonNull(methodParameter.getMethod()).isAnnotationPresent(IgnoreResponse.class);
    }

    @Override
    @SneakyThrows
    public Object beforeBodyWrite(
            Object body,
            @NonNull MethodParameter returnType,
            @NonNull MediaType selectedContentType,
            @NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
            @NonNull ServerHttpRequest request,
            @NonNull ServerHttpResponse response
    ) {
        if (body instanceof String) {
            return JsonUtil.toJSONString(Result.success(body));
        }
        if (body instanceof Result) {
            return body;
        }
        return Result.success(body);
    }
}
